package org.phoenix.mall.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.phoenix.mall.admin.common.pojo.vo.CategoryVO;
import org.phoenix.mall.admin.common.utils.PagedGridResult;
import org.phoenix.mall.admin.mapper.CategoryMapper;
import org.phoenix.mall.admin.pojo.Category;
import org.phoenix.mall.admin.service.CategoryService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    private CategoryMapper categoryMapper;

    @Override
    public Category createCategory(Category category) {
        categoryMapper.insert(category);
        return category;
    }

    @Override
    public PagedGridResult getCategoryListByPage(Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<CategoryVO> list = categoryMapper.queryCategoryListByPage(0);
        if (!StringUtils.isEmpty(list)) {
            for (CategoryVO item : list) {
                item.setChildren(
                    convert(categoryMapper.queryAllChildCategoryListByPid(item.getCatId())));
            }
        }
        return setterPagedGrid(list, page);
    }

    @Override
    public List<CategoryVO> getChildCategoryList(Integer pid, Integer level) {
        List<CategoryVO> list;
        switch (level) {
            case 0:
                list = convert(categoryMapper.queryTopCategoryListByPid(pid));
                break;
            case 1:
                list = convert(categoryMapper.query2ChildCategoryListByPid(pid));
                break;
            default:
                list = convert(categoryMapper.queryAllChildCategoryListByPid(pid));
                break;
        }

        return list;
    }

    @Resource
    public void setCategoryMapper(CategoryMapper categoryMapper) {
        this.categoryMapper = categoryMapper;
    }

    private PagedGridResult setterPagedGrid(List<CategoryVO> list, Integer page) {
        PageInfo<CategoryVO> pageList = new PageInfo<>(list);
        PagedGridResult grid = new PagedGridResult();
        grid.setPage(page);
        grid.setRows(list);
        grid.setTotal(pageList.getPages());
        grid.setRecords(pageList.getTotal());
        return grid;
    }

    private List<CategoryVO> convert(List<CategoryVO> list) {
        if (list != null) {
            for (CategoryVO item : list) {
                if (item.getChildren().size() == 0) {
                    item.setChildren(null);
                } else {
                    convert(item.getChildren());
                }
            }
        }
        return list;
    }
}
